
import 'dart:typed_data';

import 'package:activity_record/model/diy_project.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:flutter_cupertino_date_picker/flutter_cupertino_date_picker.dart';

import 'package:multi_image_picker/multi_image_picker.dart';

/*
diy活动新增页面
涉及用户输入所以继承自状态可变的StatefulWidget
采用全屏对话框的形式展现
 */
class DiyAddDialog extends StatefulWidget {
  DiyAddDialog({Key key, this.db, this.diyProject}) : super(key: key);
  final db;
  final DiyProject diyProject;

  @override
  DiyAddDialogState createState() => new DiyAddDialogState();
}

class DiyAddDialogState extends State<DiyAddDialog> {
  String _title = '';

//实例化对象已选择的时间，并赋予初始值是当前时间
  // String _selectedDate = DateFormat.yMd("en_US").format(DateTime.now());
  //存放通过requestThumbnail方法返回的图片数据
  List imageDataList = [];
  //存放转换成Uint8List后的图片数据
  List imagesUnift8List = [];
  //存放将图片Uint8List数据转换成string后的数据
  List imagesUnift8StringList = [];
  String _imagePath = '';
  bool _isPaided = false;
  String _selectedDate = DateFormat('yyyy-MM-dd').format(DateTime.now());
  int year = DateTime.now().year;
  int month = DateTime.now().month;
  int date = DateTime.now().day;
  //活动名称输入框控制器
  TextEditingController _nameTextEditingController =
      new TextEditingController();
  //活动地点输入框控制器
  TextEditingController _placeTextEditingController =
      new TextEditingController();
  //活动联系人输入框控制器
  TextEditingController _contactTextEditingController =
      new TextEditingController();
  //活动单价输入框控制器
  TextEditingController _singlePriceTextEditingController =
      new TextEditingController();
  //活动份数输入框控制器
  TextEditingController _numsTextEditingController =
      new TextEditingController();
  //活动物料成本输入框控制器
  TextEditingController _itemCostTextEditingController =
      new TextEditingController();
  //活动人员成本输入框控制器
  TextEditingController _laborCostTextEditingController =
      new TextEditingController();
  //备注输入框控制器
  TextEditingController _notesTextEditingController =
      new TextEditingController();

  @override
  void dispose() {
    _nameTextEditingController.dispose();
    _placeTextEditingController.dispose();
    _contactTextEditingController.dispose();
    _singlePriceTextEditingController.dispose();
    _numsTextEditingController.dispose();
    _itemCostTextEditingController.dispose();
    _laborCostTextEditingController.dispose();
    _notesTextEditingController.dispose();
    super.dispose();
  }

  //根据是否传入diyProject进行输入控件内容的初始化
  @override
  void initState() {
    super.initState();
    if (widget.diyProject != null) {
      _selectedDate = widget.diyProject.date;
      _nameTextEditingController.text = widget.diyProject.name;
      _placeTextEditingController.text = widget.diyProject.place;
      _contactTextEditingController.text = widget.diyProject.contact;
      _singlePriceTextEditingController.text =
          widget.diyProject.singlePrcie.toString();
      _numsTextEditingController.text = widget.diyProject.nums.toString();
      _itemCostTextEditingController.text =
          widget.diyProject.itemCost.toString();
      _laborCostTextEditingController.text =
          widget.diyProject.laborCost.toString();
      _imagePath = widget.diyProject.imagePath;
      _isPaided = widget.diyProject.isPaided;
      _notesTextEditingController.text = widget.diyProject.notes;
    }
  }

  //点击保存或更新的时候如果未选取图片则弹出对话框提示
  Widget _noImageDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (context) {
          return new AlertDialog(
            title: new Text('请先选择活动照片后再保存'),
            actions: <Widget>[
              new FlatButton(
                child: new Text('确定'),
                onPressed: () => Navigator.of(context).pop(null),
              )
            ],
          );
        });
  }

  //IOS风格的日期选择器
  void _showDatePicker(BuildContext context) {
    final bool showTitleActions = true;
    DatePicker.showDatePicker(
      context,
      showTitleActions: showTitleActions,
      minYear: 1970,
      maxYear: 2020,
      initialYear: year,
      initialMonth: month,
      initialDate: date,
      locale: 'zh',
      dateFormat: 'yyyy-mmm-dd',
      onConfirm: (year, month, date) {
        _settingDatetime(year, month, date);
      },
    );
  }

  //进行根据选择的日期进行日期设置
  void _settingDatetime(int year, int month, int date) {
    setState(() {
      this.year = year;
      String m = month < 10 ? '0$month' : month.toString();
      String d = date < 10 ? '0$date' : date.toString();

      _selectedDate = '$year-$m-$d';
    });
  }

  //活动文字信息输入
  Widget _infoTextField(
      IconData icon, TextEditingController controller, String hint) {
    return Padding(
      padding: const EdgeInsets.fromLTRB(15.0, 10.0, 18.0, 0.0),
      child: new TextField(
        autofocus: true,
        controller: controller,
        decoration: new InputDecoration(icon: new Icon(icon), hintText: hint),
      ),
    );
  }

  //活动价格份数信息输入框封装
  Widget _amountTextField(TextEditingController controller, String labelText,
      String prefixText, String suffixText) {
    return new TextField(
      //键盘类型适用于登录的
      keyboardType: TextInputType.numberWithOptions(signed: true),
      controller: controller,
      /*
      输入框装饰：
      包含边框、标题、提示文本、后缀文本
      */
      decoration: new InputDecoration(
          border: OutlineInputBorder(),
          labelText: labelText,
          prefixText: prefixText,
          suffixText: suffixText,
          suffixStyle: new TextStyle(color: Colors.green)),
    );
  }

  // //从本地相册选择图片
  // Future _getImagePath() async {
  //   File imageFile = await ImagePicker.pickImage(source: ImageSource.gallery);
  //   String path = imageFile.path;
  //   if (path != null) {
  //     setState(() {
  //       _imagePath = path;
  //     });
  //   }
  // }

  //多图选择器
  _getImagePath() async {
    var requestList =
        await MultiImagePicker.pickImages(maxImages: 6, enableCamera: true);
    if (requestList.length != 0) {
      imageDataList.clear();
      for (int i = 0; i < requestList.length; i++) {
        var imageData = await requestList[i].requestThumbnail(800,600,quality: 80);
        imageDataList.add(imageData);
      }
      imagesUnift8List.clear();
      for (int i = 0; i < imageDataList.length; i++) {
        Uint8List bytes = Uint8List.view(imageDataList[i].buffer);
        imagesUnift8List.add(bytes);
      }
      setState(() {
        _imagePath = _getImageString(imagesUnift8List);
      });
    }
  }

  //根据选择图片数据拼接成存入数据库的String
  String _getImageString(List list) {
    imagesUnift8StringList.clear();
    if (list.length > 1) {
      list.forEach((value) {
        imagesUnift8StringList.add(value.join('-'));
      });
      return imagesUnift8StringList.join('&');
    } else {
      return list.first.join('-');
    }
  }

  //根据拼接的图片字符串拆分成对应的uint8list数组
  List _getUint8List(String imagePath) {
    List p = [];
    if (imagePath.contains('&')) {
      List x = imagePath.split('&');
      x.forEach((value) {
        List y = value.split('-');
        List<int> z = [];
        y.forEach((string) {
          z.add(int.parse(string));
        });
        p.add(Uint8List.fromList(z));
      });
      return p;
    } else {
      List y = imagePath.split('-');
      List<int> z = [];
      y.forEach((string) {
        z.add(int.parse(string));
      });
      p.add(Uint8List.fromList(z));
      return p;
    }
  }

  //根据输入计算总金额
  _totalAmountCalculate() {
    int _totalAmount = int.parse(_singlePriceTextEditingController.text) *
        int.parse(_numsTextEditingController.text);
    return _totalAmount;
  }

  //根据输入计算利润
  _profitCalculate() {
    int totalAmount = _totalAmountCalculate();
    int _profit = totalAmount -
        int.parse(_itemCostTextEditingController.text == ''
            ? '0'
            : _itemCostTextEditingController.text) -
        int.parse(_laborCostTextEditingController.text == ''
            ? '0'
            : _laborCostTextEditingController.text);
    return _profit;
  }

  //根据选择计算未结钱款
  _unPaidAmountCalculate() {
    if (_isPaided) {
      return 0;
    } else {
      return _totalAmountCalculate();
    }
  }

  //先根据是否传入diyProject来判断是新增还是更新
  _saveDiyItem(
      String name,
      String date,
      String place,
      String contact,
      String imagePath,
      int singlePrice,
      int nums,
      int totalAmount,
      int itemCost,
      int laborCost,
      int profit,
      int unPaidAmount,
      bool isPaided,
      String notes) async {
    //如果该页面没有diyProject传进来，说明是从首页新增按钮进来，所以是新增
    if (widget.diyProject == null) {
      DiyProject newDiyProject = new DiyProject(
          name,
          date,
          place,
          contact,
          imagePath,
          singlePrice,
          nums,
          totalAmount,
          itemCost,
          laborCost,
          profit,
          unPaidAmount,
          isPaided,
          notes);
      int savedID = await widget.db.insertDiyProject(newDiyProject);
      print('插入的savedID：$savedID');
      // DiyProject savedDiyProject = await widget.db.getDiyProject(savedID);
      // widget.diyProjects.insert(0, savedDiyProject);
      // return widget.diyProjects;
    } else {
      DiyProject diyProjectUpdated = DiyProject.fromMap({
        'id': widget.diyProject.id,
        'name': _nameTextEditingController.text,
        'date': _selectedDate,
        'place': _placeTextEditingController.text,
        'contact': _contactTextEditingController.text,
        'imagePath': _imagePath,
        'singlePrice': int.parse(_singlePriceTextEditingController.text),
        'nums': int.parse(_numsTextEditingController.text),
        'totalAmount': _totalAmountCalculate(),
        'itemCost': int.parse(_itemCostTextEditingController.text),
        'laborCost': int.parse(_laborCostTextEditingController.text),
        'profit': _profitCalculate(),
        'unPaidAmount': _unPaidAmountCalculate(),
        'isPaided': _isPaided == true ? 1 : 0,
        'notes': _notesTextEditingController.text
      });
      await widget.db.updateDiyProject(diyProjectUpdated);
      return diyProjectUpdated;
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        elevation: Theme.of(context).platform == TargetPlatform.iOS ? 0.0 : 4.0,
        title: new Text(_title),
        actions: <Widget>[
          new FlatButton(
            child: new Text(
              widget.diyProject == null ? '保存' : '更新',
              style: Theme.of(context)
                  .textTheme
                  .subhead
                  .copyWith(color: Colors.white),
            ),
            onPressed: () {
              if (_imagePath == '') {
                _noImageDialog(context);
              } else
                Navigator.of(context).pop(_saveDiyItem(
                    _nameTextEditingController.text,
                    _selectedDate,
                    _placeTextEditingController.text,
                    _contactTextEditingController.text,
                    _imagePath,
                    int.parse(_singlePriceTextEditingController.text),
                    int.parse(_numsTextEditingController.text),
                    _totalAmountCalculate(),
                    int.parse(_itemCostTextEditingController.text == ''
                        ? '0'
                        : _itemCostTextEditingController.text),
                    int.parse(_laborCostTextEditingController.text == ''
                        ? '0'
                        : _laborCostTextEditingController.text),
                    _profitCalculate(),
                    _unPaidAmountCalculate(),
                    _isPaided,
                    _notesTextEditingController.text));
            },
          )
        ],
      ),
      body: new Builder(
        builder: (BuildContext context) {
          return new SafeArea(
            top: false,
            //这个容器是用于当触���虚拟键盘后，点击区域内的空白地方转移焦点从而实现关闭虚拟键盘效果
            child: new Container(
              height: 1400.0,
              child: new GestureDetector(
                onTap: () {
                  FocusScope.of(context).requestFocus(FocusNode());
                },
                child: new ListView(
                  children: <Widget>[
                    new Padding(
                      padding:
                          const EdgeInsets.fromLTRB(15.0, 15.0, 15.0, 10.0),
                      child: new InkWell(
                        onTap: () => _showDatePicker(context),
                        child: new Container(
                          child: new Row(
                            children: <Widget>[
                              new Icon(
                                Icons.today,
                                color: Theme.of(context).primaryColor,
                                size: 25.0,
                              ),
                              new Padding(
                                padding: const EdgeInsets.only(left: 10.0),
                                child: new Text(_selectedDate),
                              )
                            ],
                          ),
                        ),
                      ),
                    ),
                    new Divider(
                      height: 0.0,
                    ),
                    new Padding(
                      padding: const EdgeInsets.fromLTRB(15.0, 10.0, 18.0, 0.0),
                      child: new TextField(
                        onChanged: (String text) {
                          setState(() {
                            _title = text;
                          });
                        },
                        autofocus: true,
                        controller: _nameTextEditingController,
                        decoration: new InputDecoration(
                            icon: new Icon(Icons.spa), hintText: '活动名称'),
                      ),
                    ),
                    _infoTextField(
                        Icons.my_location, _placeTextEditingController, '活动地点'),
                    _infoTextField(
                        Icons.face, _contactTextEditingController, '联系人'),
                    //备注输入框
                    new Padding(
                      padding: const EdgeInsets.fromLTRB(15.0,8.0,18.0,0.0),
                      child: new TextField(
                        controller: _notesTextEditingController,
                        decoration: InputDecoration(hintText: '备注：'),
                      ),
                    ),
                    new Divider(
                      height: 30.0,
                    ),
                    //把两个金额输入框放在一个包含padding的横向布局里
                    new Padding(
                      padding: const EdgeInsets.fromLTRB(18.0, 0.0, 18.0, 0.0),
                      child: new Row(
                        children: <Widget>[
                          new Expanded(
                            child: _amountTextField(
                                _singlePriceTextEditingController,
                                '活动单价',
                                '\￥',
                                'CNY'),
                          ),
                          new SizedBox(
                            width: 10.0,
                          ),
                          new Expanded(
                            child: _amountTextField(
                                _numsTextEditingController, '活动份数', '\￡', '份'),
                          ),
                        ],
                      ),
                    ),
                    //把两个金额输入框放在一个包含padding的横向布局里
                    new Padding(
                      padding:
                          const EdgeInsets.fromLTRB(18.0, 18.0, 18.0, 18.0),
                      child: new Row(
                        children: <Widget>[
                          new Expanded(
                            child: _amountTextField(
                                _itemCostTextEditingController,
                                '物料成本',
                                '\￥',
                                'CNY'),
                          ),
                          new SizedBox(
                            width: 10.0,
                          ),
                          new Expanded(
                            child: _amountTextField(
                                _laborCostTextEditingController,
                                '人员成本',
                                '\￥',
                                'CNY'),
                          ),
                        ],
                      ),
                    ),
                    new Divider(
                      height: 0.0,
                    ),
                    //欠款是否结清
                    new CheckboxListTile(
                      value: _isPaided,
                      onChanged: (value) {
                        setState(() {
                          _isPaided = value;
                        });
                      },
                      secondary: new Icon(
                        Icons.payment,
                        color:
                            _isPaided ? Theme.of(context).primaryColor : null,
                      ),
                      title: new Text('钱款已结清'),
                    ),
                    new Divider(
                      height: 0.0,
                    ),
                    //选择的图片显示
                    _imagePath == ''
                        ? new Container(
                            width: 0.0,
                            height: 0.0,
                          )
                        : Padding(
                          padding: const EdgeInsets.all(8.0),
                          child: new Wrap(
                            spacing: 1.0,
                            runSpacing: 1.0,
                            alignment: WrapAlignment.start,
                              children: _getUint8List(_imagePath).map((value) {
                                return new Image.memory(
                                  value,
                                  width: 80.0,
                                  height: 80.0,
                                  fit: BoxFit.cover
                                );
                              }).toList(),
                            ),
                        ),
                    //相册选取照片
                    new Padding(
                      padding:
                          const EdgeInsets.fromLTRB(18.0, 10.0, 18.0, 18.0),
                      child: new Row(children: <Widget>[
                        new Container(
                          height: 50.0,
                          width: 50.0,
                          decoration: new BoxDecoration(
                              border: new Border.all(color: Colors.grey),
                              borderRadius: new BorderRadius.circular(5.0)),
                          child: new InkWell(
                              onTap: () => _getImagePath(),
                              child: new Icon(
                                Icons.add,
                                size: 40.0,
                                color: Colors.grey,
                              )),
                        ),
                      ]),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
      ), //新增项目的UI
    );
  }

  // void _sendImage(String imagePath) {
  //   widget.reference.push().set({'imagePath': imagePath});
  // }

}
